package love.contact;

import love.contact.engine.TheApplication;
import wwk.common.constant.Commonstant;
import wwk.common.event.MessageManager;
import wwk.common.util.IntentUtil;
import wwk.common.widget.CustomDialog;
import wwk.common.widget.NavigationBar;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract.PhoneLookup;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import love.contact.adapter.GroupSubObjectListAdapter;
import love.contact.data.Contact;
import love.contact.data.Group;

public class MyGroupActivity extends BaseActivity implements OnItemClickListener
{	
	int i=0;
	
	private Group currentGroup;
	private GroupSubObjectListAdapter listViewAdapter;
	private ListView listView;
	
	private Handler handler = new Handler() 
	{
		@Override
		public void handleMessage(Message msg) 
		{
			super.handleMessage(msg);
			
			switch(msg.what)
			{
				case Commonstant.Message_Contact_Changed:
				{
					TheApplication theApp=(TheApplication)getApplication();
			        currentGroup=theApp.engine.currentGroup;
			        listViewAdapter.setGroup(currentGroup);
			        
			        listViewAdapter.notifyDataSetChanged();
				}
				break;
			}
		}
	};
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
        TheApplication theApp=(TheApplication)getApplication();
        currentGroup=theApp.engine.currentGroup;
        currentGroup.openSubCursor();
        
        MessageManager.instance().addHandler(handler,Commonstant.Message_Contact_Changed);

        //use layout.xml create GroupedListView
		//setContentView(R.layout.title_group_list);
		//GroupedListView groupedListView=(GroupedListView)this.findViewById(R.id.groupedListView);
		//groupedListView.setListData(data);

		//or dync create GroupedListView
		//GroupedListView  groupedListView=new GroupedListView(this,data);
		
		this.setContentView(R.layout.common_nav_list_activity);
		
		NavigationBar navigationBar=(NavigationBar)this.findViewById(R.id.navBar);
		
		View rButton=(View)navigationBar.addRightButton(R.layout.add_group_button);
        rButton.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View arg0) {
				addGroup();
			}
        	
        });
        
		String title=currentGroup.getName();
        if(title!="")
        {
        	/*
            String parentTitle=getIntent().getStringExtra("parentTitle");
            if(parentTitle!=null)
            {
            		title=parentTitle+"-"+title;
            }
            */
            
    			navigationBar.setBackButton(R.layout.common_nav_back_button);
    			
    			View addContactBtn=(View)navigationBar.addRightButton(R.layout.add_contact_button);
    			addContactBtn.setOnClickListener(new OnClickListener()
    	        {
    				@Override
    				public void onClick(View arg0) {
    					addContact();
    				}
    	        	
    	        });
        }
        else
        {
    			title=this.getString(R.string.myGroup);
        }
        
        setTitle(title);
        navigationBar.setTitle(title);

		listView=(ListView)this.findViewById(android.R.id.list);
		listView.setCacheColorHint(0);//parent when scroll
		Drawable color=new ColorDrawable(0xFF000000);//or Color.parseColor("#FFFFFF")
		listView.setDivider(color);
		listView.setBackgroundColor(Color.parseColor("#ffffff"));
		listView.setDividerHeight(1);
		listView.setTextFilterEnabled(true);

		registerForContextMenu(listView);  
		
		//adapter
		listViewAdapter=new GroupSubObjectListAdapter(this,currentGroup);
		listView.setAdapter(listViewAdapter);
		
		//listener
		listView.setOnItemClickListener(this);

		//empty view
		TextView emptyView=(TextView)findViewById(android.R.id.empty);
		emptyView.setText(this.getString(R.string.emptyGroup));
		listView.setEmptyView(emptyView); 
    }
    
    public void reload()
    {
    	 TheApplication theApp=(TheApplication)getApplication();
        currentGroup=theApp.engine.currentGroup;
        currentGroup.openSubCursor();
         
        listViewAdapter.setGroup(currentGroup);
 		listViewAdapter.notifyDataSetChanged();
    }
  
    public void onStart()
	{
		super.onStart();
	}
	
	public void onPause()
	{
		super.onPause();
	}
	
	public void onResume()
	{
		super.onResume();
	}
	
	public void onStop()
	{
		super.onStop();
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		
		currentGroup.closeCusror();
		MessageManager.instance().removeHandler(handler,Commonstant.Message_Contact_Changed);
	}
	
	@Override
	public void onBackPressed() 
	{
		super.onBackPressed();
	}
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode,Intent data) 
	{
    	TheApplication theApp=(TheApplication)getApplication();
    	theApp.engine.currentGroup=currentGroup;
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{		
		MenuItem menuItem=menu.add(0,0,0,this.getString(R.string.createGroup));
		menuItem.setIcon(R.drawable.group_add);
	
		if(currentGroup.longId.length()>0)
		{
			menuItem=menu.add(0,1,0,this.getString(R.string.addContact));
			menuItem.setIcon(R.drawable.ic_addcontact);
		}
		
		super.onCreateOptionsMenu(menu);
		
		return true;
	}
	
	private void addGroup()
	{
		//dialog
		StringBuffer groupName=new StringBuffer();
		boolean ret=CustomDialog.showQueryDialog(this, this.getString(R.string.enterGroupName), R.drawable.group_add,groupName);
		if(ret)
		{ 
			 if(groupName.length()>0)
			 {
				currentGroup.addSubGroup(groupName.toString());
				listViewAdapter.notifyDataSetChanged();
			 }
		 }
	}
	
	private void addContact()
	{
		TheApplication theApp=(TheApplication)getApplication();
		String selection=Group.ungroupedContactIdsSelectionString(theApp.engine.getPhoneBook().getSqliteUtil());
		Cursor cursor=Contact.openContactCursor(this, selection,false);
		if(cursor.getCount()>0)
		{
			ListView listView=new ListView(this);
			listView.setCacheColorHint(0);
			Drawable color=new ColorDrawable(0xFFFFFFFF);
			listView.setDivider(color);
			listView.setDividerHeight(1);
			
			SimpleCursorAdapter multiple_choice_listViewAdapter = new SimpleCursorAdapter(this,
					android.R.layout.simple_list_item_multiple_choice,
					cursor,
					new String[]{PhoneLookup.DISPLAY_NAME},
					new int[]{ android.R.id.text1});

			
			listView.setAdapter(multiple_choice_listViewAdapter);
			listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
			listView.setFastScrollEnabled(true);
			
			 CustomDialog dialog=new CustomDialog(this);
			 dialog.setTitle(this.getString(R.string.selectContacts));
			 dialog.setIcon(R.drawable.ic_addcontact);
			 dialog.setContentView(listView);
			 dialog.addButtonOk();
			 dialog.addButtonCancel();
			 int buttonIndex=dialog.showWithBlock();
			 if(buttonIndex==0)
			 {
				 SparseBooleanArray sparseBooleanArray=listView.getCheckedItemPositions();
				 int size=sparseBooleanArray.size();
				 for(int i=0;i<size;i++)
				 {
					 int index=sparseBooleanArray.keyAt(i);
					 
					 //deselect after select,check again
					 if(listView.getCheckedItemPositions().get(index))
					 {
						 cursor.moveToPosition(index);
						 int contactId=Contact.getContactId(cursor);
						 currentGroup.addSubContact(contactId);
					 }
				 }
				 listViewAdapter.notifyDataSetChanged();
			 }
		 }
		else
		{
			CustomDialog.showAlertDialog(this, this.getString(R.string.emptyUngroupedContact));
		}
		cursor.close();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		super.onOptionsItemSelected(item);
		
		int itemId=item.getItemId();
		switch(itemId)
		{
			case 0:
				{
					addGroup();
				}
				break;
			case 1:
				{
					addContact();
				}
				break;
			case 2:
				{
					/*
					//create contact
					Intent intent = new Intent(Intent.ACTION_INSERT);
			        intent.setType("vnd.android.cursor.dir/person");
			        intent.setType("vnd.android.cursor.dir/contact");
			        intent.setType("vnd.android.cursor.dir/raw_contact");
			        //intent.putExtra("phone", "76582"); 
			        startActivity(intent);
			        */
				}
				break;
		}
		 
		return true;
	}

	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		
		 AdapterView.AdapterContextMenuInfo adapterContextMenuInfo =(AdapterView.AdapterContextMenuInfo)menuInfo;
	     int listPosition=adapterContextMenuInfo.position-listView.getHeaderViewsCount();
	    if(listPosition<currentGroup.subGroupCount())
	    {
	    	Group group=currentGroup.subGroupAtIndex(listPosition);
	    	menu.setHeaderIcon(R.drawable.ic_group);
	    	menu.setHeaderTitle(group.getName());
			menu.add(0, 0, 0, R.string.modifyGroupName);  
			menu.add(0, 1, 0, R.string.revocationGroup);  
	    }
	    else
	    {
	    	//int contactId=currentGroup.subContactId(this, listPosition-currentGroup.subGroupCount());
	    	String contactName=((TextView)adapterContextMenuInfo.targetView).getText().toString();
	    	menu.setHeaderIcon(R.drawable.ic_contact);
			menu.setHeaderTitle(contactName);
			menu.add(0, 0, 0, R.string.removeFromGroup); 
	    }
	}
	
	public boolean onContextItemSelected(MenuItem item)
	{
		 AdapterView.AdapterContextMenuInfo menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
	     int listPosition=menuInfo.position;
	     
	     if(listPosition<currentGroup.subGroupCount())
	     { 
	    	Group currentSubGroup=currentGroup.subGroupAtIndex(listPosition);
	    	 
			int itemId=item.getItemId();
			switch(itemId)
			{
				case 0:
					{
						StringBuffer buffer=new StringBuffer(currentSubGroup.getName());
						boolean ret=CustomDialog.showQueryDialog(this,getString(R.string.enterGroupName),R.drawable.ic_group, buffer);
						if(ret)
						{
							currentSubGroup.setName(buffer.toString());
							currentSubGroup.update();
							
							listViewAdapter.notifyDataSetChanged();
						}
					}
					break;
				case 1:
					{
						boolean b=CustomDialog.showSelectDialog(this,getString(R.string.confirmRevocationGroup));
						if(b)
						{
							currentSubGroup.delete();
							listViewAdapter.notifyDataSetChanged();
						}
					}
				case 2:
					{
						/*
						//������鲢ɾ���Ա
						*/
						
						/*
						//�ƶ�����
						*/
						
						/*
						//�ƶ���Ա
						*/
						
						/*
						//�ƶ���Ա���������
						*/
					}
				break;
			}
	     }
	     else
	     {
	    	 listPosition=listPosition-currentGroup.subGroupCount();
	    	 int contactId=currentGroup.subContactId(this, listPosition);
	    	 
	    	 int itemId=item.getItemId();
			switch(itemId)
			{
				case 0:
					{
						boolean b=CustomDialog.showSelectDialog(this,getString(R.string.confirmRemoveContact));
						if(b)
						{
							currentGroup.removeSubContact(contactId);
							listViewAdapter.notifyDataSetChanged();
						}
					}
					break;
				case 1:
					{
						/*
						//�ӷ����Ƴ�ɾ��
						Contact contact=currentGroup.removeSubContact(listPosition,Engine.getInstance().getPhoneBook().getUngroupedContactArray(),
				        		Engine.getInstance().getPhoneBook().getUngroupedContactIdArray());
						contact.delete(this);
						listViewAdapter.notifyDataSetChanged();
						*/
					}
				break;
			}
	     }
		
		return super.onContextItemSelected(item);
	}
	
	public void onItemClick(AdapterView<?> parent, View view, int position,long id) 
	{
		position-=listView.getHeaderViewsCount();
		if(position<currentGroup.subGroupCount())
		{
			Intent intent=new Intent();
			TheApplication theApp=(TheApplication)getApplication();
			theApp.engine.currentGroup=currentGroup.subGroupAtIndex(position);
			intent.setClass(MyGroupActivity.this,MyGroupActivity.class);
			if(currentGroup.getName()!="")
			{
				intent.putExtra("parentTitle",getTitle()); 
			}
			int requestCode=0;
			startActivityForResult(intent, requestCode);
		}
		else
		{
			int index=position-currentGroup.subGroupCount();
			int contactId=currentGroup.subContactId(this, index);
			if(Contact.isContactExists(this, contactId))
			{
				IntentUtil.startContactViewActivity(this,contactId);
			}
			else
			{
				currentGroup.removeSubContact(contactId);
				listViewAdapter.notifyDataSetChanged();
				
				Toast.makeText(this, "��ϵ����ɾ��", Toast.LENGTH_SHORT).show();
			}
			//���peopleId�ķ���
			//sim������People.CONTENT_URI��鵽��People._ID
			//�ֻ���Uri.parse("content://icc/adn")��鵽��People._ID
		}
	}
	
}